<?php
class DbFarmConnPool {
	static public $DEFAULT_PORT = 3306;

	private $connPool;
	private $farms;
	private $farmTotal;
	private $dbUser;
	private $dbPwd;
	private $dbName;

	public function __construct($configFile) {
		$config= ConfigReaderFactory::getInstance()->getConfigReader($configFile)->getConfig();
		$this->dbUser = (string) $config->dbFarms->user[0];
		$this->dbPwd = (string) $config->dbFarms->pwd[0];
		$this->dbName = (string) $config->dbFarms->name[0];
		$this->farms = array();
		foreach ($config->dbFarms->farm as $farm) {
			$farmId = (int) $farm->attributes()->id;
			$tmp = array();
			$tmp['writer'] = (string) $farm->writer[0];
			foreach ($farm->readers->reader as $reader) {
				$tmp['readers'][] = (string) $reader;
			}
			$tmp['maxReaderIndex'] = count($tmp['readers']) - 1;
			$this->farms[$farmId] = $tmp;
		}
		$this->farmTotal = count($this->farms);
	}
	
	public function getFarmTotal() {
		return $this->farmTotal;
	}
	
	public function getReadConn($farmId) {
		return $this->_getConn($this->farms[$farmId]['readers'][rand(0, $this->farms[$farmId]['maxReaderIndex'])]);		
	}
	
	public function getWriteConn($farmId) {
		return $this->_getConn($this->farms[$farmId]['writer']);
	}
	
	protected function _getConn($dbHost) {
		if (!isset($this->connPool[$dbHost])) {
			$tmp = explode(':', $dbHost);
			$host = $tmp[0];
			$port = isset($tmp[1]) ? $tmp[1] : self::$DEFAULT_PORT;
			$this->connPool[$dbHost] = new PDO("mysql:host={$host};port={$port};dbname={$this->dbName}", $this->dbUser, $this->dbPwd);
			$this->connPool[$dbHost]->exec("SET NAMES utf8");
		}
		
		return $this->connPool[$dbHost];
		
	}
	
	public function clearPool() {
		$this->connPool = null;
	}
}
?>
